<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.workcenter_delete" @click="handleDelete">删 除 </el-button>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/admin/workcenter';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';

export default {
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      model: {}, //与option内column匹配的prop相互绑定
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        menuWidth: 200, //弹框内字段宽度属性
        dialogWidth: 880, //弹框宽度属性
        labelWidth: '110',
        dialogClickModal: false,
        column: [
          {
            label: '车间类型',
            // 生产车间/维修车间/包装车间
            prop: 'centerType',
            search: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=center_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请输入车间类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '中心编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入中心编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '中心名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入中心名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '负责人',
            prop: 'principal',
            // bind: "principal", 此属性不能对同层级的使用点语法点出来
            type: 'search',
            disabled: true,
            rules: [
              {
                required: false,
                message: '请输入负责人',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openUserCommonModal();
            }
          },
          {
            label: '联系方式',
            prop: 'contacts',
            rules: [
              {
                required: false,
                message: '请输入联系方式',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '长',
            prop: 'length',
            type: 'number',
            rules: [
              {
                required: false,
                message: '请输入长',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '宽',
            prop: 'width',
            type: 'number',
            rules: [
              {
                required: false,
                message: '请输入宽',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '高',
            prop: 'height',
            type: 'number',
            rules: [
              {
                required: false,
                message: '请输入高',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '最近通知',
            prop: 'latestNotice',
            rules: [
              {
                required: false,
                message: '请输入最近通知',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '地址信息',
            // 显示地址名称,传参地址ID
            prop: 'locationName',
            bind: 'location.name', //绑定对象层级中的值
            type: 'search',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择地址信息',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLocationCommonModal();
            }
          },
          {
            label: '组织名称',
            // 显示组织名称，传递组织ID
            prop: 'orgId',
            type: 'select',
            dicUrl: '/api/mes-admin/organization/lazy-list',
            props: {
              label: 'name',
              value: 'id'
            },
            rules: [
              {
                required: true,
                message: '请选择组织名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '工厂名称',
            // 实体ID, SITE_ID，如工厂，仓库等
            prop: 'siteName',
            bind: 'site.name',
            type: 'search',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择工厂名称',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openSiteCommonModal();
            }
          },
          {
            label: '是否库存中心',
            // 是否库存中心，如果是，则可以规划库位等
            prop: 'isInventory',
            type: 'switch', //开关的类型
            align: 'center',
            width: 100,
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ],
            value: 0,
            slot: true,
            rules: [
              {
                required: true,
                message: '请选择是否为库存中心',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '货位段数',
            prop: 'locatorSegments',
            type: 'number',
            rules: [
              {
                required: false,
                message: '请输入货位段数',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '详细描述',
            // 文本域
            prop: 'description',
            type: 'textarea',
            minRows: 4, //定义多行文本最小行数
            span: 24, //在表单中单独定义栅列
            overHidden: true,
            row: true,
            hide: true
          }
        ]
      },
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      data: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.workcenter_add, false),
        viewBtn: this.vaildData(this.permission.workcenter_view, false),
        delBtn: this.vaildData(this.permission.workcenter_delete, false),
        editBtn: this.vaildData(this.permission.workcenter_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 打开位置管理选择模态框
     */
    openLocationCommonModal() {
      this.modalName = 'locationModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择位置信息（双击进行选择）',
        url: '/api/mes-admin/location/page?status=0',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '地址名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '国家',
            prop: 'country',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '省份',
            prop: 'province'
          },
          {
            label: '城市',
            prop: 'city'
          }
        ]
      };
    },
    /**
     * 打开工厂管理选择模态框
     */
    openSiteCommonModal() {
      this.modalName = 'siteModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择工厂管理信息（双击进行选择）',
        url: '/api/mes-admin/site/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '代码',
            prop: 'code',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '工厂类型',
            prop: 'siteType'
          },
          {
            label: '子类型',
            prop: 'subType'
          }
        ]
      };
    },
    /**
     * 打开用户管理选择模态框
     */
    openUserCommonModal() {
      this.modalName = 'userModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择用户管理信息（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '用户姓名',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '所属部门',
            prop: 'deptName',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '职务',
            prop: 'postName'
          },
          {
            label: '用户平台',
            prop: 'userTypeName'
          }
        ]
      };
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      // if (this.modalName === 'locationModal') {
      //     this.form.locationId = this._get(rowData, 'id', '');
      //     this.form.locationName = this._get(rowData, 'name', '');
      // } else if (this.modalName === 'siteModal') {
      //     this.form.siteId = this._get(rowData, 'id', '');
      //     this.form.siteName = this._get(rowData, 'name', '');
      // } else if (this.modalName === 'userModal') {
      //     this.form.principal = this._get(rowData, 'id', '');
      //     this.form.principalName = this._get(rowData, 'name', '');
      // }
      switch (this.modalName) {
        case 'locationModal':
          this.form.locationId = this._get(rowData, 'id', '');
          this.form.locationName = this._get(rowData, 'name', '');
          break;
        case 'siteModal':
          this.form.siteId = this._get(rowData, 'id', '');
          this.form.siteName = this._get(rowData, 'name', '');
          break;
        case 'userModal':
          this.form.principal = this._get(rowData, 'id', '');
          this.form.principalName = this._get(rowData, 'name', '');
          break;
        default:
          break;
      }
    },
    rowSave(form, done, loading) {
      add(form).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(form, index, done, loading) {
      update(form).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style></style>
